package start;

import decoder.RtmpDecoder;
import eventloop.MessageEventLoopGroup;
import handler.RtmpHandler;
import handler.RtmpOutHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

// ffmpeg -re  -stream_loop -1 -i test11.mp4 -vcodec copy -acodec copy -f flv -y rtmp://127.0.0.1:9999/live/123
public class RtmpServer {
    public static void main(String[] args) {
        System.out.println("启动rtmp server");
        start(9999);
    }

    public static void start(int port){
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        final MessageEventLoopGroup messageGroup = new MessageEventLoopGroup();
        final NioEventLoopGroup videoGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup,workGroup).
                    channel(NioServerSocketChannel.class).
                    childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new RtmpDecoder(videoGroup, messageGroup));
                            socketChannel.pipeline().addLast(new RtmpOutHandler());
                            socketChannel.pipeline().addLast(new RtmpHandler());
                        }
                    })
                    .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(32768, 65536))
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(4096));
            Channel ch = serverBootstrap.bind(port).sync().channel();
            ch.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            videoGroup.shutdownGracefully();
        }
    }
}
